function Promise(executor) {

    //保存实例对象的 this 的值
    const self = this; // self _this that 潜规则保存this的值

    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;

    //添加回调
    this.callbacks = []

    //resolve 函数 判断状态/赋值
    function resolve(data) {
        //判断状态只能修改一次
        if (self.PromiseState !== 'pending') return
        //1.修改对象的状态(promiseState)
        self.PromiseState = 'fulfilled'; // resolved与fulfilled都代表成功
        //2.设置对象结果值(promiseResult)
        self.PromiseResult = data
        //调用成功的回调函数
        self.callbacks.forEach(item => {
            item.onResolved(data);
        })
    }

    //reject 函数 判断状态/赋值
    function reject(data) {
        //判断状态只能修改一次
        if (self.PromiseState !== 'pending') return
        //1.修改对象的状态(promiseState)
        self.PromiseState = 'rejected'; // 失败
        //2.设置对象结果值(promiseResult)
        self.PromiseResult = data
        //调用失败的回调函数
        self.callbacks.forEach(item => {
            item.onRejected(data);
        })
    }

    try {
        //同步调用(执行器函数)
        executor(resolve, reject)
    } catch (e) {
        //修改 promise 对象状态为失败
        reject(e)
    }
}

//添加 then 方法
Promise.prototype.then = function (onResolved, onRejected) {
    return new Promise((resolve, reject) => {
        // 调用回调函数 通过PromiseState判断执行
        if (this.PromiseState == 'fulfilled') {
            try {
                //获取回调函数的执行结果
                let result = onResolved(this.PromiseResult);
                if (result instanceof Promise) {
                    //如果是Promise对象
                    result.then(v => {
                        resolve(v);
                    }, r => {
                        reject(r)
                    })
                } else {
                    //结果的状态为成功
                    resolve(result);
                }
            } catch (e) {
                reject(e)
            }
        }

        if (this.PromiseState == 'rejected') {
            onRejected(this.PromiseResult);
        }

        //判断pending状态
        if (this.PromiseState == 'pending') {
            //保存回调函数
            this.callbacks.push({
                onResolved,
                onRejected
            })
        }
    })
}

// --------------------------------------- //
// --------------------------------------- //
// --------------------------------------- //
let p = new Promise((resolve, reject) => {// resolve 决定 reject 拒绝
    // resolve('ok');
    // reject('error');
    setTimeout(() => {
        resolve('ok');
        // reject('error');
    }, 1000)
    //抛出异常
    // throw "exception"
})


let res = p.then(value => {
    //返回值为非promise类型数据时都为成功
    //返回值是一个promise对象,那返回的数据与promise返回的状态一致
    // return 'hello Promise'
    // return new Promise((resolve, reject) => {
    //     // resolve('success');
    //     // reject('oh no');
    //     //抛出异常
    //     throw "FAIL"
    // })
    // throw "FAIL"
}, reason => {
    console.log(reason);
})